package queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 用队列实现栈
 */
public class ImplementStackUsingQueues {
  public static void main(String[] args) {
    MyStack stack = new MyStack();
    stack.push(1);
    stack.push(2);
    System.out.println(stack.top());
  }
}

class MyStack {

  private Queue<Integer> bufferQueue1;
  private Queue<Integer> bufferQueue2;


  /**
   * Initialize your data structure here.
   */
  public MyStack() {
    bufferQueue1 = new LinkedList<>();
    bufferQueue2 = new LinkedList<>();
  }

  /**
   * Push element x onto stack.
   */
  public void push(int x) {
    //有两个队列，如果两个队列都为空，则往bufferQueue1添加，
    // 如果一个为空，一个不为空，则往不为空的队列中添加元素
    if ((bufferQueue1.isEmpty()) && (!bufferQueue2.isEmpty())) {
      bufferQueue2.offer(x);
    } else if ((!bufferQueue1.isEmpty()) && (bufferQueue2.isEmpty())) {
      bufferQueue1.offer(x);
    } else if ((bufferQueue1.isEmpty()) && (bufferQueue2.isEmpty())) {
      bufferQueue1.offer(x);
    }
  }

  /**
   * Removes the element on top of the stack and returns that element.
   */
  public int pop() {
    if (this.empty() == true) {
      return -1;
    }
    //bufferQueue1不为空，bufferQueue2不为空
    if (!bufferQueue1.isEmpty() && bufferQueue2.isEmpty()) {
      while (bufferQueue1.size() != 1) {
        bufferQueue2.offer(bufferQueue1.poll());
      }
      return bufferQueue1.poll();
    }
    //bufferQueue2不为空，bufferQueue1为空
    if (bufferQueue1.isEmpty() && !bufferQueue2.isEmpty()) {
      while (bufferQueue2.size() != 1) {
        bufferQueue1.offer(bufferQueue2.poll());
      }
      return bufferQueue2.poll();
    }
    return -1;
  }

  /**
   * Get the top element.
   */
  public int top() {
    if (this.empty() == true) {
      return -1;
    }
    //bufferQueue1不为空，bufferQueue2不为空
    if (!bufferQueue1.isEmpty() && bufferQueue2.isEmpty()) {
      while (bufferQueue1.size() != 1) {
        bufferQueue2.offer(bufferQueue1.poll());
      }
      int tmp = bufferQueue1.poll();
      bufferQueue2.offer(tmp);
      return tmp;
    }
    if (bufferQueue1.isEmpty() && !bufferQueue2.isEmpty()) {
      while (bufferQueue2.size() != 1) {
        bufferQueue1.offer(bufferQueue2.poll());
      }
      int tmp = bufferQueue2.poll();
      bufferQueue1.offer(tmp);
      return tmp;
    }
    return -1;
  }

  /**
   * Returns whether the stack is empty.
   */
  public boolean empty() {
    return ((bufferQueue1.isEmpty()) && (bufferQueue2.isEmpty())) ? true : false;
  }
}
